package com.hycat.mail.order.config;

import com.alibaba.fastjson.JSON;
import com.hycat.mail.order.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : lzhycat
 * @date : 2022-08-24 11:36
 * order-MQ 配置
 */
@Configuration
@Slf4j
public class MyRabbitMQConfig {

    private final static Logger logger = LoggerFactory.getLogger(MyRabbitMQConfig.class);

    //test
    @RabbitListener(queues = "order.release.queue")
    public void test(OrderEntity orderEntity) {
        logger.info("本次监听的消息是 {}", JSON.toJSONString(orderEntity));
    }

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * @return 死信队列
     */
    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "order-event-exchange");
        arguments.put("x-dead-letter-routing-key", "order.release.order");
        arguments.put("x-message-ttl", 1800000); // 消息过期时间 30分钟

        return new Queue(
                "order.delay.queue",
                true,
                false,
                false, arguments);
    }

    /**
     * @return 消费队列
     */
    @Bean
    public Queue orderReleaseQueue() {
        return new Queue(
                "order.release.order.queue",
                true,
                false,
                false);
    }

    /**
     * @return (死信交换机 + 正常交换机) 一体机
     */
    @Bean
    public Exchange orderEventExchange() {
        return new TopicExchange(
                "order_event_exchange",
                true,
                false);
    }

    /**
     * @return 绑定交换机、死信队列
     */
    @Bean
    public Binding orderCreatBinding() {
        return new Binding("order.delay.queue",
                Binding.DestinationType.QUEUE,
                "order_event_exchange",
                "order.creat.order",
                null);
    }

    /**
     * @return 绑定交换机、消费队列
     */
    @Bean
    public Binding orderReleaseBinding() {
        return new Binding("order.release.order.queue",
                Binding.DestinationType.QUEUE,
                "order_event_exchange",
                "order.release.order",
                null);
    }


}
